//
//  YWNoticeDBManager.m
//  maintain
//
//  Created by kyo on 16/11/8.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWNoticeDBManager.h"
#import "YWDBTool.h"
#import "YWCommonTool.h"

#import "YWReply.h"
#import "YWReplyDBManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

@implementation YWNoticeDBManager
YWSingletonM(Manager)

- (FMDatabase*)fmdb{
    return [[YWDBTool shareDBTool] fmdb];
}
- (FMDatabaseQueue*)dbQeue{
    return [[YWDBTool shareDBTool] dbQeue];
}

#pragma mark - 公告

NSString* const KSqlCreateNoticeTable = @"CREATE TABLE IF NOT EXISTS 'notice' (noticeId integer UNIQUE,title text,content text,fromUserId integer,receivers text,receiverIds varchar,organizationNos varchar,createTime timestamp,workSequence text,observerIds varchar);";

- (BOOL)createNoticeTable
{
    NSString* sql = KSqlCreateNoticeTable;
    return [[self fmdb] executeUpdate:sql];
}

- (void)dropAndReCreateNoticeTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists notice;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateNoticeTable];
        }
    }];
}

- (BOOL)updateNoticeWithNoticeArray:(NSArray*)notices
{
    __block BOOL executeResult = YES;
    __block NSArray* blockNotices = notices;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        
        [blockNotices enumerateObjectsUsingBlock:^(YWNotice* _Nonnull notice, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'notice' WHERE noticeId=? ;";
            FMResultSet* set = [db executeQuery:sql, @(notice.noticeId)];
            if ([set next]) {
                sql = @"UPDATE 'notice' SET title=? ,content=? ,fromUserId =?,receivers=?,receiverIds=?,organizationNos=?, createTime=?,workSequence=?,observerIds=? WHERE noticeId=?;";
                executeResult = [db executeUpdate:sql, notice.title, notice.content, @(notice.fromUser.uniqueId), notice.receivers,notice.receiverIds,notice.organizationNos, @(notice.createTime),notice.workSequence, notice.observerIds,@(notice.noticeId)];
            }
            else {
                sql = @"INSERT INTO 'notice' (noticeId,title,content,fromUserId,receivers,receiverIds,organizationNos,createTime,workSequence,observerIds) VALUES (?, ?, ?, ? ,?, ?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql, @(notice.noticeId), notice.title, notice.content, @(notice.fromUser.uniqueId), notice.receivers,notice.receiverIds,notice.organizationNos, @(notice.createTime),notice.workSequence,notice.observerIds];
            }
            //这里是防止别人修改通知图片，把图片删除光了，在更新图片的时候没有删除
            if (notice.imagesList.count==0) {
                NSString* sql = @"delete FROM 'record_picture' WHERE recordId=?";
                executeResult = [db executeUpdate:sql, @(notice.noticeId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    
    __block NSMutableArray* picturesArray = [NSMutableArray array];
    __block NSMutableArray* attachmentsArray = [NSMutableArray array];
//    __block NSMutableArray* replysArray = [NSMutableArray array];
    [blockNotices enumerateObjectsUsingBlock:^(YWNotice* _Nonnull notice, NSUInteger idx, BOOL* _Nonnull stop) {
        //图片
        [notice.imagesList enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull patrolPicture, NSUInteger idx, BOOL* _Nonnull stop) {
            patrolPicture.recordId = [NSString stringWithFormat:@"%ld", (long)notice.noticeId];
            patrolPicture.uploadStatus = YWPictureRecordUploadStatusSuccess;
            patrolPicture.recordType = YWPictureRecordTypeNotice;
        }];
        [picturesArray addObjectsFromArray:notice.imagesList];
        
        //附件
        [notice.attachmentList enumerateObjectsUsingBlock:^(YWattachment* _Nonnull attachment, NSUInteger idx, BOOL* _Nonnull stop) {
            attachment.recordId = notice.noticeId;
            attachment.attachmentType = YWattachmentTypeOfNotice;
        }];
        [attachmentsArray addObjectsFromArray:notice.attachmentList];
        
//        //评论
//        [notice.workReplyList enumerateObjectsUsingBlock:^(YWReply*  _Nonnull reply, NSUInteger idx, BOOL * _Nonnull stop) {
//            reply.relationId = notice.noticeId;
//            reply.relationType = YWReplyRelationTypeNotice;
//        }];
//        [replysArray addObjectsFromArray:notice.workReplyList];
        
        //保存发布人
        if (notice.fromUser) {
            [[YWDBTool shareDBTool] updateHandlerWithArray:@[ notice.fromUser ]];
        }
    }];
    [[YWDBTool shareDBTool] updatePatrolPictureWithNewWorkData:picturesArray];
    [[YWDBTool shareDBTool] updateAttachmentWithAttachments:attachmentsArray];
//    [[YWReplyDBManager shareManager] updateReplyWithReplyArray:replysArray];
    return executeResult;
}

- (NSArray*)noticesOfTypeWithMeOrOthers:(YWNoticeType)noticeType page:(NSInteger)page
{
    __block NSMutableArray* blockNoticeArray = [NSMutableArray array];
    __block YWLoginUser* currentUser = [YWLoginTool loginUser];
    __block NSString* sql = @"";
    __block NSInteger showCount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        FMResultSet* set = nil;
        if (noticeType == YWNoticeTypeOfAll) {
            sql = @"SELECT * FROM 'notice' ORDER BY createTime desc  LIMIT ?";
        }
        else {
            if (noticeType == YWNoticeTypeOfMe) {
                sql = @"SELECT * FROM 'notice' where fromUserId=? ORDER BY createTime desc  LIMIT ?";
            }
            else {
                sql = @"SELECT * FROM 'notice' where fromUserId!=? ORDER BY createTime desc  LIMIT ?";
            }
        }
        if (noticeType == YWNoticeTypeOfAll) {
            set = [db executeQuery:sql, @(showCount)];
        }
        else {
            set = [db executeQuery:sql, @(currentUser.uniqueId), @(showCount)];
        }
        
        //按照时间排序后，分时间段显示，构建二维数组
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWNotice* notice = [self noticeWithFMResultSet:set FMDatabase:db];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:notice.createTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:notice];
            if (![blockNoticeArray containsObject:array] && array.count) {
                [blockNoticeArray addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    //    for (YWNotice* notice in blockNoticeArray) {
    //        NSMutableArray* handlers = [NSMutableArray array];
    //        NSArray* list = [notice.toUserIds componentsSeparatedByString:@","];
    //        for (int i = 0; i < list.count; i++) {
    //            NSInteger userId = [list[i] integerValue];
    //            YWHandler* handler = [self handlerWithUniqueId:userId];
    //            if (handler) {
    //                [handlers addObject:handler];
    //            }
    //        }
    //        notice.toUserArray = handlers;
    //    }
    return blockNoticeArray.count ? blockNoticeArray : nil;
}

- (YWNotice*)noticeWithNoticeId:(NSInteger)noticeId
{
    __block YWNotice* notice = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'notice' where noticeId=? ";
        FMResultSet* set = [db executeQuery:sql, @(noticeId)];
        while ([set next]) {
            notice = [self noticeWithFMResultSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return notice;
}

- (BOOL)existNoticeWithNoticeId:(NSInteger)noticeId{
    __block BOOL ret = NO;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* selectSQL = @"SELECT * FROM 'notice' WHERE noticeId=?;";
        FMResultSet* set = [db executeQuery:selectSQL,@(noticeId)];
        if ([set next]) {
            ret = YES;
        }
        [db closeOpenResultSets];
    }];
    return ret;
}

- (BOOL)deleteNoticeWithNoticeId:(NSInteger)noticeId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"DELETE FROM 'notice' where noticeId=? ";
        executeResult = [db executeUpdate:sql, @(noticeId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)deletePictureOfNoticeWithNoticeId:(NSInteger)noticeId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"delete FROM 'record_picture' WHERE recordId=?";
        executeResult = [db executeUpdate:sql, @(noticeId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWNotice*)noticeWithFMResultSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWNotice* notice = [[YWNotice alloc] init];
    notice.noticeId = [set intForColumn:@"noticeId"];
    notice.title = [set stringForColumn:@"title"];
    notice.content = [set stringForColumn:@"content"];
    notice.createTime = [set longLongIntForColumn:@"createTime"];
    notice.receivers = [set stringForColumn:@"receivers"];
    notice.receiverIds = [set stringForColumn:@"receiverIds"];
    notice.workSequence = [set stringForColumn:@"workSequence"];
    notice.observerIds = [set stringForColumn:@"observerIds"];
    notice.organizationNos = [set stringForColumn:@"organizationNos"];
    
    NSInteger creatorId = [set intForColumn:@"fromUserId"];
    NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    FMResultSet *newSet = [db executeQuery:sql, @(creatorId)];
    if ([newSet next]) {
        notice.fromUser = [[YWDBTool shareDBTool] handlerWithSet:newSet];
    }
    NSMutableArray *observer = [NSMutableArray array];
    sql = [NSString stringWithFormat:@"SELECT * FROM 'handler' WHERE uniqueId in (%@)",notice.observerIds];
    newSet = [db executeQuery:sql];
    while ([newSet next]) {
        YWHandler *handler = [[YWDBTool shareDBTool] handlerWithSet:newSet];
        [observer addObject:handler];
    }
    notice.observers = observer;
    return notice;
}

@end
